/**
  * Copyright @ 2019 HoldTime Inner Mongolia Co. Ltd.
  */ 
package com.holdtime.jtt809dataservice.server.processor;

import com.edata.common.BytesUtil;
import com.holdtime.jtt809dataservice.common.event.MessageReceiveEvent;
import com.holdtime.jtt809dataservice.common.process.ProtocolProcessor;
import com.holdtime.jtt809dataservice.server.socket.TcpClient;
import com.holdtime.jtt809dataservice.server.util.LinksManager;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import protocol.jtt809.JTT809Packet;
import protocol.jtt809.ProtocolJT809;
import protocol.jtt809.body.DownLinktestRsp;
import protocol.jtt809.body.RawBody;

/** 
 * 项目名称： jtt809gateway<br>
 * 功能描述： DownLinktestRspProcessor概述：从链路连接保持应答处理<br>
 * 创  建 人： guoai<br>
 * 创建日期： 2019年7月29日<br>
 * 修  改 人：  <br>
 * 修改时间：<br>
 * 修改内容：<br>
 * 版      本： 1.0.0
 */
@Component
@Slf4j
public class DownLinktestRspProcessor implements ProtocolProcessor {
    @Resource
    private ProtocolJT809 protocolJT809;

    @Override
    public int getMsgID() {
        return DownLinktestRsp.MSG_ID;
    }

    @Override
    public void process(MessageReceiveEvent event) {
        try {
            JTT809Packet<RawBody> source = event.getSource();
            DownLinktestRsp rsp = new DownLinktestRsp();
            JTT809Packet<DownLinktestRsp> packet = protocolJT809.getPacket(rsp, DownLinktestRsp.MSG_ID, source.getMsgGnsscenterid());
            TcpClient tcpClient = LinksManager.getSubLink(source.getMsgGnsscenterid());
            if (tcpClient.connect()) {
                byte[] bytes = packet.array();
                log.error("发送从链路连接保持给下级平台：{}", BytesUtil.changebytetohexstring(bytes));
                tcpClient.send(bytes);
            }else{
                LinksManager.removeSubLink(source.getMsgGnsscenterid());
            }
            
        } catch (Exception e) {
            log.error("从链路连接保持请求处理异常：", e);
        }
    }

}
